package serialization;

import java.io.*;
import java.util.ArrayList;

public class Test1 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //方法1
        writeStu();
        readStu();
        //方法2
        //写一次,读一次
        Student s1 = new Student("张三",19);
        Student s2 = new Student("李四",89);
        Student s3 = new Student("瓦伦丁",29);
        ArrayList<Student> list = new ArrayList<>();
        list.add(s1);
        list.add(s2);
        list.add(s3);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("HDay09\\stu.txt"));
        oos.writeObject(list);
        oos.close();
        //读
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("HDay09\\stu.txt"));
        //向下转型，本来读出的是Object类型，转为ArrayList类型
        ArrayList<Student> list1 = (ArrayList<Student>) ois.readObject();
        for (Student student : list1) {
            System.out.println(student);
        }
        ois.close();
    }

    private static void readStu() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("HDay09\\stu.txt"));
        //他的结尾是报异常，这里直接抓异常break
        while(true){
            try {
                Object o1 = ois.readObject();
                System.out.println(o1);
            } catch (EOFException e) {
                break;
            }
        }
        ois.close();
    }

    private static void writeStu() throws IOException {
        Student s1 = new Student("张三",19);
        Student s2 = new Student("李四",89);
        Student s3 = new Student("瓦伦丁",29);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("HDay09\\stu.txt"));
        oos.writeObject(s1);
        oos.writeObject(s2);
        oos.writeObject(s3);
        oos.close();
    }
}
